package com.ruoyi.web.controller.api;

import com.ruoyi.api.dto.SearchActivityResultDto;
import com.ruoyi.api.dto.SearchClubResultDto;
import com.ruoyi.api.service.IMiniActivityService;
import com.ruoyi.api.service.IMiniSearchService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.directory.SearchResult;
import java.util.List;

@Controller
@RequestMapping("/api/search" )
public class MiniSearchController extends BaseController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private IMiniSearchService searchService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 搜索结果获取
     */
    @GetMapping(value = "/getSearchResult" )
    @ResponseBody
    public AjaxResult getActivityInfo(@RequestParam("searchText") String searchText) {
        // 获取搜索活动结果
        List<SearchActivityResultDto> activityResultDtoList = searchService.searchActivityByName(searchText);
        // 获取搜索社团结果
        List<SearchClubResultDto> clubResultDtoList = searchService.searchClubByName(searchText);
        AjaxResult ajaxResult = new AjaxResult();

        if (!activityResultDtoList.isEmpty() || !clubResultDtoList.isEmpty()) {
            try {
                this.amqpTemplate.convertAndSend("exchange.searchText","a.b", searchText);
            } catch (Exception e) {
                logger.error("RabbitMq异常", e);
                ajaxResult.put("activityResult", activityResultDtoList);
                ajaxResult.put("clubResult", clubResultDtoList);
                return AjaxResult.success(ajaxResult);
            }
        }
        ajaxResult.put("activityResult", activityResultDtoList);
        ajaxResult.put("clubResult", clubResultDtoList);
        return AjaxResult.success(ajaxResult);
    }

    /**
     * 获取热搜词汇
     */
    @GetMapping(value = "/getHotSearchText" )
    @ResponseBody
    public AjaxResult getHotSearchText() {
        try {
            List<SearchResult> cacheList = redisCache.getCacheList(Constants.HOT_SEARCH_KEY);
            if (cacheList.isEmpty()) {
                throw new RuntimeException();
            }
            return AjaxResult.success(cacheList);
        } catch (Exception e) {
            List<String> hotSearchText = searchService.getHotSearchText();
            redisCache.setCacheList(Constants.HOT_SEARCH_KEY,hotSearchText);
            return AjaxResult.success(hotSearchText);
        }
    }

}
